package com.xcjw.com.Activity;

import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.xcjw.com.Adapter.MyDocumentAdapter;
import com.xcjw.com.Base.BasesActivitys;
import com.xcjw.com.Base.Myapplication;
import com.xcjw.com.Bean.AddMeetResponse;
import com.xcjw.com.Bean.AddcarBean;
import com.xcjw.com.Bean.CarBean;
import com.xcjw.com.Bean.CarResponse;
import com.xcjw.com.Bean.CarSearchBean;
import com.xcjw.com.Bean.LoginUser;
import com.xcjw.com.Http.HttpUrl;
import com.xcjw.com.R;
import com.xcjw.com.Utils.FileUtils;
import com.xcjw.com.Utils.JsonUtil;
import com.xcjw.com.Utils.KeyboardUtils;
import com.xcjw.com.Utils.StatusBarUtil;
import com.xcjw.com.Utils.TimeFormatUtils;
import com.xcjw.com.Utils.ToastUtils;
import com.xcjw.com.View.SimpleTool;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @packname com.xcjw.com.Activity
 * @filename AddCarActivity
 * @date on 2018/11/22 19:31
 *****/
public class AddCarActivity extends BasesActivitys implements View.OnClickListener, PopupWindow.OnDismissListener {

      @BindView(R.id.image)
      ImageView image;
      @BindView(R.id.txt_left_title)
      TextView txtLeftTitle;
      @BindView(R.id.txt_main_title)
      TextView txtMainTitle;
      @BindView(R.id.txt_right_titleS)
      TextView txtRightTitleS;
      @BindView(R.id.txt_right_title)
      TextView txtRightTitle;
      @BindView(R.id.simple_toolbar)
      SimpleTool simpleToolbar;
      @BindView(R.id.yd_time)
      TextView ydTime;
      @BindView(R.id.start_time)
      EditText startTime;
      @BindView(R.id.end_time)
      EditText endTime;
      @BindView(R.id.yd_didian)
      TextView ydDidian;
      @BindView(R.id.hy_content)
      EditText hyContent;
      @BindView(R.id.zb_shixiang)
      EditText zbShixiang;
      @BindView(R.id.sb_date)
      TextView sbDate;
      @BindView(R.id.sb_reason)
      EditText sbReason;
      @BindView(R.id.sb_bumen)
      EditText sbBumen;
      @BindView(R.id.submit)
      Button submit;
      private LoginUser.ContentBean user;
      private int height;
      private String s3;
      private PopupWindow popupWindow;
      private View view;
      private ListView listView;
      private View rootview;
      private List<CarSearchBean.ContentBean.CarTypeListBean> list;
      private CarResponse.ContentBean detail;

      @Override
      protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            StatusBarUtil.setRootViewFitsSystemWindows(this, false);
            StatusBarUtil.setTranslucentStatus(this);
            setContentView(R.layout.addcar_activity);
            ButterKnife.bind(this);
            int result = 0;
            int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                  result = this.getResources().getDimensionPixelSize(resourceId);
            }
            int flags = getIntent().getFlags();
            detail = (CarResponse.ContentBean) getIntent().getSerializableExtra("detail");

            WindowManager wm = this.getWindowManager();
            Point point = new Point();
            wm.getDefaultDisplay().getSize(point);
            int width = point.x;
            height = point.y;
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) image.getLayoutParams();
            params.height = result;
            params.width = width;
            image.setLayoutParams(params);
            Myapplication.getInstance().addActivity(this);
            user = (LoginUser.ContentBean) FileUtils.getObject(AddCarActivity.this, "loginUser");

            searchcar();
            txtLeftTitle.setOnClickListener(this);
            submit.setOnClickListener(this);
            txtMainTitle.setText("用车申请");
            ydTime.setOnClickListener(this);
            ydDidian.setOnClickListener(this);
            submit.setOnClickListener(this);
            list = new ArrayList<>();
            if (detail != null) {
                  ydTime.setText(detail.getUseCarTime() == null ? "" : detail.getUseCarTime());
                  startTime.setText(detail.getNumberOfPeople() == null ? "" : detail.getNumberOfPeople() + "");
                  endTime.setText(detail.getDestination() == null ? "" : detail.getDestination());
                  ydDidian.setText(detail.getCarTypeName() == null ? "" : detail.getCarTypeName());
                  hyContent.setText(detail.getMainContent() == null ? "" : detail.getMainContent());
            }

      }

      @Override
      public void onClick(View v) {
            switch (v.getId()) {
                  case R.id.txt_left_title:
                        onBackPressed();
                        break;
                  case R.id.yd_time:
                        if (KeyboardUtils.isSoftShowing(AddCarActivity.this)) {
                              KeyboardUtils.close(AddCarActivity.this);

                        }
                        showDateDialog(ydTime, "请选择用车时间");
                        break;
                  case R.id.yd_didian:
                        if (KeyboardUtils.isSoftShowing(AddCarActivity.this)) {
                              KeyboardUtils.close(AddCarActivity.this);
                              openPopupWindow(ydDidian, "请选择车型", list);
                        }
                        openPopupWindow(ydDidian, "请选择车型", list);
                        break;
                  case R.id.submit:
                        if (verco()) {
                              postMeet();
                        }
                        break;
            }
      }

      private boolean verco() {
            if (TextUtils.isEmpty(ydTime.getText().toString())) {
                  ToastUtils.shorttoast(AddCarActivity.this, "用车时间不能为空");
                  return false;
            }

            if (TextUtils.isEmpty(startTime.getText().toString())) {
                  ToastUtils.shorttoast(AddCarActivity.this, "用车人数不能为空");
                  return false;
            }
            if (TextUtils.isEmpty(endTime.getText().toString())) {
                  ToastUtils.shorttoast(AddCarActivity.this, "目的地不能为空");
                  return false;
            }
            if (TextUtils.isEmpty(ydDidian.getText().toString())) {
                  ToastUtils.shorttoast(AddCarActivity.this, "车型不能为空");
                  return false;
            }
            if (TextUtils.isEmpty(hyContent.getText().toString())) {
                  ToastUtils.shorttoast(AddCarActivity.this, "用车事由不能为空");
                  return false;
            }
            return true;
      }


      private void openPopupWindow(final TextView v, String s, final List<CarSearchBean.ContentBean.CarTypeListBean> list) {
            //防止重复按按钮
            if (popupWindow != null && popupWindow.isShowing()) {
                  popupWindow.dismiss();
            }
            //设置PopupWindow的View
            view = LayoutInflater.from(AddCarActivity.this).inflate(R.layout.view_popupwindow, null);
            popupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.WRAP_CONTENT,
                      RelativeLayout.LayoutParams.WRAP_CONTENT);
            TextView title = (TextView) view.findViewById(R.id.text_title);
            title.setText(s);
            listView = (ListView) view.findViewById(R.id.list_content);
            //设置背景,这个没什么效果，不添加会报错
            MyDocumentAdapter adapter = new MyDocumentAdapter(this, list);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                  @Override
                  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        v.setText(list.get(position).getCarType());
                        popupWindow.dismiss();

                  }
            });
            adapter.notifyDataSetChanged();
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            //设置点击弹窗外隐藏自身
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            //设置动画
            popupWindow.setAnimationStyle(R.style.PopupWindow);
            //设置位置
            rootview = LayoutInflater.from(AddCarActivity.this).inflate(R.layout.addcar_activity, null);
            popupWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
            //设置消失监听
            popupWindow.setOnDismissListener(this);
            //设置PopupWindow的View点击事件
            setOnPopupViewClick(view);
            //设置背景色
            setBackgroundAlpha(0.3f);
      }

      private void setOnPopupViewClick(View view) {
            TextView tvcancel = (TextView) view.findViewById(R.id.tv_cancel);
            tvcancel.setOnClickListener(this);

      }

      //设置屏幕背景透明效果
      public void setBackgroundAlpha(float alpha) {
            WindowManager.LayoutParams lp = this.getWindow().getAttributes();
            lp.alpha = alpha;
            getWindow().setAttributes(lp);
      }

      @Override
      public void onDismiss() {
            setBackgroundAlpha(1);
      }

      private void showDateDialog(final TextView birthday, final String s) {
            Calendar selectedDate = Calendar.getInstance();
            final Calendar startDate = Calendar.getInstance();
            final Calendar endDate = Calendar.getInstance();
            //正确设置方式 原因：注意事项有说明
            endDate.set(2050, 1, 1);
            final long l = System.currentTimeMillis();
            TimePickerView timepicker = new TimePickerView.Builder(AddCarActivity.this, new TimePickerView.OnTimeSelectListener() {
                  @Override
                  public void onTimeSelect(Date date, View v) {
                        String s1 = TimeFormatUtils.ms2DateOnlyDay(date.getTime());
                        long l1 = System.currentTimeMillis();
                        String s2 = TimeFormatUtils.ms2DateOnlyDay(l1);
                        int i = TimeFormatUtils.compare_date(s1, s2);
                        if (i <= 0) {
                              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                              s3 = sdf.format(date);
                              birthday.setText(sdf.format(date));
                        } else {
                              ToastUtils.shorttoast(AddCarActivity.this, "请选择大于当前时间");
                        }


                  }
            }).setSubmitText("确定").setCancelText("取消").setDividerColor(Color.GRAY).isCyclic(true).setOutSideCancelable(true)
                      .isCenterLabel(true)
                      .setTitleText(s)
                      .setTitleColor(getResources().getColor(R.color.sss))
                      .setTitleSize(15)
                      .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                      .setRangDate(startDate, endDate)
                      .build();
            timepicker.setDialogOutSideCancelable(true);
            timepicker.setDate(Calendar.getInstance());
            timepicker.show();
      }

      void postMeet() {
            AddcarBean bean = new AddcarBean();
            bean.setId(user.getId());
            if (detail != null) {
                  bean.setArrangeCheckId(detail.getId());
            }
            bean.setUseCarTime(ydTime.getText().toString());
            bean.setNumberOfPeople(Integer.parseInt(startTime.getText().toString()));
            bean.setCarType(ydDidian.getText().toString());
            bean.setDestination(endTime.getText().toString());
            bean.setMainContent(hyContent.getText().toString());
            OkHttpUtils.post(HttpUrl.Url + HttpUrl.SAVECAR).upJson(JsonUtil.tojson(bean)).execute(new StringCallback() {
                  @Override
                  public void onSuccess(String s, Call call, Response response) {
                        if (response.code() == 200) {
                              AddMeetResponse addMeetResponse = JsonUtil.parseJsonToBean(s, AddMeetResponse.class);
                              if (addMeetResponse.getCode().equals("0")) {
                                    ToastUtils.shorttoast(AddCarActivity.this, addMeetResponse.getMessage());
                                    onBackPressed();
                              } else {
                                    ToastUtils.shorttoast(AddCarActivity.this, addMeetResponse.getMessage());
                              }

                        } else {
                              ToastUtils.shorttoast(AddCarActivity.this, "网络繁忙，稍后重试");
                        }
                  }
            });


      }

      void searchcar() {
            CarBean bean = new CarBean();
            bean.setId(user.getId());
            OkHttpUtils.post(HttpUrl.Url + HttpUrl.SEARCHCAR).upJson(JsonUtil.tojson(bean)).execute(new StringCallback() {
                  @Override
                  public void onSuccess(String s, Call call, Response response) {
                        if (response.code() == 200) {
                              CarSearchBean addMeetResponse = JsonUtil.parseJsonToBean(s, CarSearchBean.class);
                              if (addMeetResponse.getCode().equals("0")) {
                                    if (addMeetResponse.getContent().getCarTypeList() != null) {
                                          list.addAll(addMeetResponse.getContent().getCarTypeList());
                                    }

//                                    ToastUtils.shorttoast(AddCarActivity.this, addMeetResponse.getMessage());
//                                    onBackPressed();
                              } else {
                                    //ToastUtils.shorttoast(AddCarActivity.this, addMeetResponse.getMessage());
                              }

                        } else {
                              ToastUtils.shorttoast(AddCarActivity.this, "网络繁忙，稍后重试");
                        }
                  }
            });


      }
}